<?php
namespace app\exam\model;

use app\common\model\Mysql;

class ExamScheduleManager extends Mysql
{
    const ACCEPT_EXAM = 0;
    const UNACCEPT_EXAM = 1;
    const OUT_EXAM = 2;

    const DB_NAME = "exam_schedule";

    const REPEAT_CREATE_EXAM = "重复创建考试";
    public function __construct()
    {
        parent::__construct();
        $this->checkExamStatus();
    }

    protected function checkExamStatus(){
        //超时的考试或者人数爆满的考试改变状态
        $sql = "select * From ".self::DB_NAME." where status<2 and date<'".gettime()."'";
        //current_mount=total_mount"; or date<'".gettime()."')";

        $result = $this->getExamScheduleAllByCustom(null,$sql);

        if($result){
            foreach ($result as $key=>$value){
                $this->updateExamScheduleByCustom($value,array("status"=>self::OUT_EXAM));
            }
        }

        $sql = "select * From ".self::DB_NAME." where status=0 and current_mount=total_mount";

        $result = $this->getExamScheduleAllByCustom(null,$sql);

        if($result){
            foreach ($result as $key=>$value){
                $this->updateExamScheduleByCustom($value,array("status"=>self::UNACCEPT_EXAM));
            }
        }
    }

    public function getExamScheduleByStatus($status=self::ACCEPT_EXAM){

        return $this->getExamScheduleAllByCustom(array("status"=>$status));
    }

    public function deleteExamScheduleById($id){
        return $this->deleteSQLbyCustom(self::DB_NAME,array("id"=>$id));
    }

    protected function updateExamScheduleByCustom($saveCondition,$saveSequence=[]){
        return $this->updateSQLbyCustom(self::DB_NAME, $saveCondition,$saveSequence);
    }

    protected function createExamScheduleByCustom($saveSequence=[],$sql=null){
        //判断是否重复创建考试
        if($this->getExamScheduleByCustom(array("id"=>$saveSequence["id"]))){
            echoJson(0, self::REPEAT_CREATE_EXAM);
        }

        return $this->createSQLbyCustom(self::DB_NAME,$saveSequence,$sql);
    }

    protected function getExamScheduleByCustom($customKey=[],$sql=null){
        return $this->selectSQLbyCustom(self::DB_NAME,$customKey,$sql);
    }

    protected function getExamScheduleAllByCustom($customKey=[],$sql=null,$page=null){
        return $this->selectSQLAllbyCustom(self::DB_NAME,$customKey,$sql,$page);
    }
}